﻿/**
 * ...
 * @author Sergey Mamyan
 */

package tx.squirrel.neko.core.model;

import neko.db.Object;
import tx.facebook.core.Facebook;
import tx.facebook.methods.AdminMethods;
import tx.squirrel.neko.core.handler.FBAppHandler;
import tx.utils.Utils;

class Application extends Object {
	
	public static var manager = new ApplicationManager();
	
	public var id:String;
	public var apiKey:String; 
	public var apiSecret:String; 
	public var canvasName:String; 
	public var displayName:String;
	public var description:String; 
	public var iconUrl:String; 
	public var logoUrl:String; 
	public var companyName:String; 
	public var category:String; 
	public var subcategory:String; 
	
	public var dailyActiveUsers:Int; 
	public var weeklyActiveUsers:Int; 
	public var monthlyActiveUsers:Int; 
		
	public function new() {
		super();
	}
	
	override public function insert() {
		super.insert();
	}
	
	override public function update() {
		super.update();
	}
	
	override public function toString():String {
		return "Application { \n\t name : " + displayName + "\n}";
	}
	
	/*
	private function updateFBData() {
		Facebook.init(apiKey, apiSecret);
		var props:Dynamic = Facebook.admin.getAppProperties(ApplicationProperties.all());
		var propsFields:Iterator<String> = Reflect.fields(props).iterator();
		while (propsFields.hasNext()) {
			var fld:String  = propsFields.next();
			var fldt:String = Utils.toClassFieldString(fld);
			Reflect.setField(this,fldt,Reflect.field(props,fld));
		}
	}
	*/
	
	public function getHandler():FBAppHandler {
		var clazzName:String = Utils.toClassPackageString(canvasName) + ".FacebookHandler";
		var clazz:Class <FBAppHandler> = cast Type.resolveClass(clazzName);
		var handler:FBAppHandler = cast Type.createInstance(clazz, []);
		return handler;
	}
	
	public function getAdminHandler():FBAppHandler {
		var clazzName:String = Utils.toClassPackageString(canvasName) + ".AdminHandler";
		var clazz:Class <FBAppHandler> = cast Type.resolveClass(clazzName);
		var handler:FBAppHandler = cast Type.createInstance(clazz, []);
		return handler;
	}
}

class ApplicationManager extends neko.db.Manager < Application > {
	public function new () {
		super(Application);
	}
	
	public function getById( appId:String ) : Application {
		return object(select("id='"+appId+"'"), true);
	}
	
	public function getByApiKey( apiKey:String ) : Application {
		return object(select("id='"+apiKey+"'"), true);
	}
}
